// XDictDlg.cpp : implementation file
//

#include "stdafx.h"
#include "XDict.h"
#include "XDictDlg.h"
#include "math.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CXDictDlg dialog

CXDictDlg::CXDictDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CXDictDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CXDictDlg)
	m_word = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CXDictDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CXDictDlg)
	DDX_Control(pDX, IDC_WORD, m_cword);
	DDX_Control(pDX, IDC_WORD_DATA, m_worddata);
	DDX_Control(pDX, IDC_WORD_LIST, m_wordlist);
	DDX_Control(pDX, IDC_WORD_MEAN, m_wordmean);
	DDX_Text(pDX, IDC_WORD, m_word);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CXDictDlg, CDialog)
	//{{AFX_MSG_MAP(CXDictDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_LBN_DBLCLK(IDC_WORD_LIST, OnDblclkWordList)
	ON_EN_CHANGE(IDC_WORD, OnChangeWord)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CXDictDlg message handlers

BOOL CXDictDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	FILE *inFile;
	inFile = fopen ("vietduc12k.index","r");
	if (inFile == NULL)
	{
		MessageBox ("Cannot openun index file");
	}
	else
	{
		char * line; // tao mot con tro line
		char lineBuf[100];
		line = (char *) lineBuf;// con tro line tro den 1 chuoi co 100 ky tu

		m_wordlist.ResetContent();
		m_worddata.ResetContent();
		CString word = "";
		CString sWord = "";
		CString sData = "";
		while (!feof(inFile))
		{
			fgets(line,99,inFile);
			if (strlen(line)>=2)
			{
				word = line;
				int pos = word.Find("\t",0);
				sWord = word.Left(pos);
				sData = word.Mid(pos+1,word.GetLength()-pos-1);
				if (sData.Find("\n",0) > 0){
					sData = sData.Left(sData.GetLength()-1);
				}
				if (sWord.GetLength()>=1)
				{
					m_wordlist.AddString(sWord);
					m_worddata.AddString(sData);
				}
			}
		}
	}
	fclose(inFile);
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CXDictDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CXDictDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CXDictDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

int GetDemicalValue (CString str)
{
	CString base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	int decValue = 0;
	int len = str.GetLength();
	for (int i = 0; i<len; i++)
	{
		int pos = base64.Find(str.GetAt(i),0);
		decValue += (int)pow(64.0,len-i-1)*pos;
	}
	return decValue;
}

CString ChangeStyle(CString wordmean)
{
	CString meaning = wordmean;
	meaning = meaning.Right(meaning.GetLength()-1);
	int pos = meaning.Find("\n",1);
	meaning.Insert(pos,"</b>");
	meaning = "<b>" + meaning;
	meaning.Replace("\n","<br>");
	meaning.Replace("{","<font color=\"#FF0000\"><b>");
	meaning.Replace("}","</b></font>");
	meaning.Replace("[","<font color=\"#FF0000\"><b>");
	meaning.Replace("]","</b></font>");
	meaning.Replace('+',' ');
	return meaning;
}

BOOL CXDictDlg::GetMeaning ()
{
	CFile f;
	CString meaning="";
	if (f.Open("vietduc12k.dict",CFile::modeRead) == FALSE)
	{
		meaning = "Không mở được file dữ liệu!";
	}
	else
	{
		CString sOffLen;
		m_worddata.GetText(m_wordlist.GetCurSel(),sOffLen);
		int pos = sOffLen.Find("\t",0);
		CString sOff = sOffLen.Left(pos);
		CString sLen = sOffLen.Right(sOffLen.GetLength()-pos-1);
		int iOff = GetDemicalValue(sOff);
		int iLength = GetDemicalValue(sLen);

		int temp = f.Seek(iOff,CFile::begin);
		char buff[64];
		DWORD dwRead;
		do
		{
			if (iLength>=64)
				dwRead = f.Read(buff,64);
			else 
				dwRead = f.Read(buff,iLength);
			iLength -= dwRead;
			CString stemp = buff;
			stemp = stemp.Left(dwRead);
			meaning += stemp;
		}while (iLength>0);
		f.Close();
	}
	meaning = ChangeStyle(meaning);
	CString strHtml("");
	strHtml += "<html>\n<head>\n";
	strHtml += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n";
	strHtml += "</head>\n<body>\n";
	

	strHtml += meaning + "\n</body>\n</html>";
	CFile f2;
	if (f2.Open("temp.htm",CFile::modeCreate | CFile::modeWrite) == FALSE){
		MessageBox("Cannot write meaning file!","Error!");
		return 0;
	}

	f2.Write(strHtml,strHtml.GetLength());
	f2.Close();

	return 1;
}


void CXDictDlg::OnDblclkWordList() 
{
	// TODO: Add your control notification handler code here
	BOOL gm = GetMeaning();
	if (gm)
	{
		m_wordlist.GetText(m_wordlist.GetCurSel(),m_word);
		UpdateData(FALSE);
		// Lay duong dan cua thu muc hien thoi
		DWORD cchCurDir; 
		LPTSTR lpszCurDir;
		TCHAR buffer[MAX_PATH];
		lpszCurDir = buffer; 
		GetCurrentDirectory(MAX_PATH, lpszCurDir); 
		CString str = lpszCurDir;
		str = "file://"+str+"\\temp.htm";

		//Hien thi nghia cua tu
		m_wordmean.Navigate(str,NULL,NULL,NULL,NULL);
	}
	else 
	{
		MessageBox("Can't get the meaning of the word"); 
	}
}


void CXDictDlg::OnChangeWord() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	m_wordlist.SelectString(-1,m_word);
}
